require "handler_http"  --启用http服务扩展
require "handler_event" --启用事件通知扩展
require "handler_proxy" --启用事件通知扩展

-- tcp客户端示例
local function client()
	local tcp = net.connect("::1", 9000, 0)
	Log(2, "connect", tcp)

	local client_connected = true
	local function logic()
		local i = 0
		while client_connected do
			tcp:send("hello world ".. i)
			Log(2, "client send", "hello world ".. i)
			i = i + 1
			sleep(5000)
		end
	end

	local co = coroutine.create(logic)
	coroutine.resume(co)

	while tcp do
		local msg = tcp:recv()
		if msg == "" then
			break
		end
		--Log(2, "client recv:", msg)
	end
	tcp:close()
	client_connected = false
	Log(2, "client close")
end


-- tcp服务端示例
local function server()
	local listener = net.listen("::", 9000)
	Log(2, "listen", listener)
	while listener do
		local tcp = listener:accept()
		Log(2, "accept", tcp)

		local function server_handle(tcp)
			while tcp do
				local msg = tcp:recv()
				if msg == "" then
					break
				end
				Log(2, "server recv:", msg)
				-- print("server recv:"..msg)
				tcp:send(msg)
			end
			tcp:close()
			Log(2, "server close")
		end

		local co = coroutine.create(server_handle)
		coroutine.resume(co, tcp)
	end
end

Log(2, "init")

--通过协程启动，服务器和客户端
-- local server_co = coroutine.create(server)
-- local ret, msg = coroutine.resume(server_co)
-- if ret == false then
-- 	Log(3, ret, msg)
-- end
-- local client_co = coroutine.create(client)
-- ret, msg = coroutine.resume(client_co)
-- if ret == false then
-- 	Log(3, ret, msg)
-- end

